package com.woniu.liuzhougov.businessproject.controller;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.woniu.liuzhougov.businessproject.dto.BusinessProjectDTO;
import com.woniu.liuzhougov.businessproject.dto.BusinessProjectInitDTO;
import com.woniu.liuzhougov.businessproject.pojo.BusinessProject;
import com.woniu.liuzhougov.businessproject.pojo.County;
import com.woniu.liuzhougov.businessproject.service.BusinessProjectService;
import com.woniu.liuzhougov.businessproject.service.CountyService;
import com.woniu.liuzhougov.businessproject.vo.BusinessProjectUploadVO;
import com.woniu.liuzhougov.businessproject.vo.Result;
import com.woniu.liuzhougov.fileManage.constant.SysConstant;
import com.woniu.liuzhougov.fileManage.controller.FileManageController;
import com.woniu.liuzhougov.fileManage.pojo.FileData;
import com.woniu.liuzhougov.fileManage.service.FileService;
import com.woniu.liuzhougov.relatedinformation.controller.AbstractRelatedInformationController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.invoke.SerializedLambda;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 招商事项管理控制器
 *
 */
@RequestMapping("businessProject")
@Controller
public class BusinessProjectController {

    @Autowired
    private BusinessProjectService businessProjectService;

    @Autowired
    private CountyService countyService;

    @Autowired
    private FileService fileService;

    @Value("${upload.path}")
    private String filePath;

    /**
     * 查找所有招商项目
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    @RequiresPermissions(value = "businessProject_listBusinessprojects")
    public Result list(){
        //从数据库查询所有的招商项目
        List<BusinessProjectDTO> businessProjects = businessProjectService.selectBusinessProjects();
        //将项目返回到table
        Result result = new Result(businessProjects);
        return result;
    }

    /**
     * 查找所属县名
     */
    @RequestMapping("/getCountyName")
    @ResponseBody
    public List getCounty(String areaId){
        List<County> countylistByAreaId = countyService.getCountyByAreaId(areaId);
        return countylistByAreaId;
    }

    /**
     * 搜索项目
     */
    @RequestMapping("/search")
    @ResponseBody
    @RequiresPermissions(value = "businessProject_searchBusinessproject")
    public Result search(BusinessProject businessProject){
        List<BusinessProjectDTO> businessProjectDTOS = businessProjectService.selectProject(businessProject);
        Result result = new Result(businessProjectDTOS);
        return result;
    }

    /**
     * 添加项目
     */
    @RequestMapping("/addBusinessProject")
    @ResponseBody
    @RequiresPermissions(value = "businessProject_searchBusinessproject")
    public Result add(BusinessProject businessProject){
        if (businessProjectService.addBusinessProject(businessProject)>0){
            return new Result("200");
        }else{
            return new Result("500");
        }
    }

    /**
     * 根据ID初始化修改表单默认值
     */
    @RequestMapping("/initUpdateForm")
    @ResponseBody
    @RequiresPermissions(value = "businessProject_updateBusinessproject")
    public BusinessProjectInitDTO initUpdateForm(String businessProjectId){
        return businessProjectService.initUpdateForm(Integer.parseInt(businessProjectId));
    }

    /**
     * 更新项目信息
     */
    @RequestMapping("/update")
    @ResponseBody
    @RequiresPermissions(value = "businessProject_updateBusinessproject")
    public Result updateBusinessProject(BusinessProject businessProject){
        if (businessProjectService.updateBusinessProject(businessProject)>0){
            return new Result("200");
        }else{
            return new Result("500");
        }
    }

    /**
     * @param: deletelist要删除的id数组
     * @return: 操作结果
     */
    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = "businessProject_deleteBusinessproject")
    public Result delete(@RequestParam(value="deletelist[]")Integer[] deletelist){
        int i = 0;
        for (Integer id:deletelist
                ) {
            if ( businessProjectService.deleteByPrimaryKey(id)!=0){
                i++;
            }
        }
        if (i > 0){
            return new Result("200");
        }else{
            return new Result("500");
        }
    }

    /**
     * 文件上传
     * @param file
     * @param request
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping("/upload")
    @ResponseBody
    @RequiresPermissions(value = "businessProject_uploadBusinessproject")
    public com.woniu.liuzhougov.common.utils.Result upload(MultipartFile file, HttpServletRequest request) throws IOException,IllegalStateException {
        //文件名uuid
        String filename = file.getOriginalFilename();
        String filenameUUID = UUID.randomUUID().toString()+","+filename;

        FileData fileData = SysConstant.getFileData();

        Boolean SaveStatus = saveToLocal(file,filenameUUID);

        Boolean DBstatus = saveToDB(fileData,file,filenameUUID);

        Boolean BusinessUpdateFile = updateFileID(filenameUUID);

        if (SaveStatus && DBstatus){
            SysConstant.code = 200;
            return com.woniu.liuzhougov.common.utils.Result.success(200,"成功");
        }else {
            SysConstant.code = 500;
            return  com.woniu.liuzhougov.common.utils.Result.error(500,"失败");
        }
    }

    private Boolean updateFileID(String filenameUUID) {
        FileData uploadFile = fileService.selectFileByName(filenameUUID);
        BusinessProject businessProject = businessProjectService.selectProjectByID(SysConstant.fileDataId);
        if (uploadFile!=null){
            if (businessProject.getFileId()==null || "".equals(businessProject.getFileId())){
                businessProject.setFileId(String.valueOf(uploadFile.getFileId()));
            }else{
                businessProject.setFileId(businessProject.getFileId()+","+ uploadFile.getFileId());
            }
        }
        int i = businessProjectService.updateBusinessProject(businessProject);
        if (i > 0){
            return true;
        }else{
            return false;
        }
    }

    public Boolean saveToDB(FileData fileData, MultipartFile file,String filenameUUID) {
        fileData.setFileName(filenameUUID);
        fileData.setFileUrl(filePath);
        fileData.setFileSize(String.valueOf(file.getSize()));
        fileData.setFileLoaderId(1);    //登录用户id
        fileData.setItemId(9);
        if (fileService.uploadFile(fileData)>0){
            return true;
        }
        return false;
    }

    public Boolean saveToLocal(MultipartFile file,String filenameUUID) {
        String filename =file.getOriginalFilename();
        String path = filePath;
        //文件夹判断
        File filepackage = new File(path);
        if (!filepackage.exists()){
            filepackage.mkdirs();
        }
        //文件防重名 File.separator用于区分windows下的/
        path = path+File.separator+filenameUUID;
        return saveFile(filepackage,path,file);
    }

    public Boolean saveFile(File filepackage, String path, MultipartFile file) {
        filepackage = new File(path);
        try {
            file.transferTo(filepackage);   //写入数据
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            SysConstant.isInsert = false;
            return  false;
        }
    }


    /**
     * 文件保存到数据库
     * @param fileData
     * @return
     */
    @RequestMapping("/addFile")
    @ResponseBody
    @RequiresPermissions(value = "businessProject_uploadBusinessproject")
    public com.woniu.liuzhougov.common.utils.Result addFile(BusinessProjectUploadVO fileData){
        SysConstant.setFileDataId(fileData);
        if (SysConstant.code == 200){
            return com.woniu.liuzhougov.common.utils.Result.success(200,"成功");
        }else {
            return com.woniu.liuzhougov.common.utils.Result.error(500,"失败");
        }
    }
}